package com.neu.servlet.ww;

import com.alibaba.fastjson.JSONObject;
import com.neu.service.ww.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "ChangeNumServlet",urlPatterns = "/ChangeNumServlet.do")
public class ChangeNumServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String g_id=request.getParameter("g_id");
        String num=request.getParameter("num");
        int disNum=new Integer(request.getParameter("disNum"));
        System.out.println(disNum);
        if (1<disNum&&disNum<10){
            GoodsService goodsService=new GoodsService();
            int row=goodsService.doUpdateNumById(g_id,num);
            if (row > 0) {
            HttpSession session=request.getSession();
            List<Map<String,Object>> carList= (List<Map<String, Object>>) session.getAttribute("carList");
            for (int i = 0; i < carList.size(); i++) {
                if (carList.get(i).get("G_ID").toString().equals(g_id)){
                    carList.get(i).put("num",Integer.parseInt(carList.get(i).get("num").toString())+Integer.parseInt(num));
                }
            }

        }else {
            PrintWriter pw=response.getWriter();
            Map<String,String> infos=new HashMap<>(16);
            infos.put("infos","库存不足");
            String json=JSONObject.toJSONString(infos);
            pw.write(json);
            pw.close();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
